package me.zhengjie.modules.biz.util;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;


public class WxMiniProgramSigner {
  private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
  private static final String KEY_ALGORITHM = "RSA";

  private static final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNLCLp7dza6PQN" +
          "DOREX0HsGzcUeGm1kFAosPQWhx7ANUj60NEwScpFxeGHY2NJNyMUvzO7R1ZRmRUg" +
          "QbpTczn14TOpLJb3iNB9nb4Q5eqUtkPf0HhhAbTzvUb1iO7xLWfPaG8PH1E+DRmc" +
          "VKJJrQnqfQoPd2WJAp0qLnkiYeMwXtvGmCYtRFcBs0UUAKKo8IJH687Gx/XsXsIS" +
          "aWRPjCKSfrozvLPVBEmUnZ/FMrRKD38XqurCzb8njQAnoGKDUxg7JBtUAuQgdxGa" +
          "MPqI6nk85BhFtYzzJmRIT5X0qBTSa7EktsABX3fGWCSMULUqJ1AvksP34se6brak" +
          "55VO6E1tAgMBAAECggEBAJ+JglyEKQfPvHWpYJYJvCjrwJiaSRh1bt81OZeK2c57" +
          "oJPna8IwnqhChmvQTJPR2+V2B7PIdMZeUp8SfOAG6TrYMmOJ2JoCOJx03CYnoZCh" +
          "aYXPhMtpmFsvAs5J/AJtXBtbCYCoyXOGnDODW+4OL3e2YuxD2x/+eFcka+zgUNh6" +
          "hSmgF7yfHXfBIo4ciO/MEP5/warX1CRXzAbg0TTjXPpKE8qzTAPnK2D+/eJwrDgT" +
          "eLlq+zumeUg4QKZ4hLc7vkPYuZCN/YRiE0g6ybSgvM3sdmEaAMS2n1oXrvvzQzdI" +
          "ppJehlK8FgmEuZGPe5bevkyWgdeojOSAQV6uqIbKYgECgYEA9CAjkaHFk9mFq4NY" +
          "pYBdivgp/apXsCD++tKWzMj6HBUp5bhhiADwYaMIdDtj0qgfpg0lCh8/F2XI6tV5" +
          "6o5die3X9yzYGvCprgvNm68eYSPKNGXbqCMZLYhKJvHy3OXfGAigW4YAVyF4hYgI" +
          "WH5+eQNsq0XpJS5qW6M4Ykn8+IkCgYEA1ybzkZZkWRsA28yfMULVCCM5fzv6myx9" +
          "Wuh4DAsWt9AA7SIuxP2JQny+P4uA1580pXRw4DQlf2oRM07PCveb/RAtDGUuF00P" +
          "vdkRYGGASqlpR+AXIaoTn6NfKzwV6nfc575DHmMV8MqtSjAK41mfkjuOmBoCxmjo" +
          "HR8uuJP5rMUCgYBiZV3QwgJvwDn3Ul51fpK1g6bxHipvzCzZje3IJq1giksz0yhE" +
          "eBRrVhn/NzzZ2HfBJwUp2kREuvrLZDXai306LcphTwrfeOb7Rridqmy1PIawrelm" +
          "EJeCWa+BmP2JeYF9H2T63rzeYZhBQf4TJRD216GCOxBosxedTeFZBHdY+QKBgGD1" +
          "9ejTrQ+XItDrq4aIxvbu4PedMTiDWU8B2zAaQze9bt1vfUJbvGMRUq/Sj9MctZ4n" +
          "FsOD3K5KP8wupRIdOthWVOb0Jkxr9z8otzMHXcjIBmFU9Te/rS5Rcw9J+dp8ADsU" +
          "PK1SHE4zGNuJQS7qcgZ1/rI/bqa6GnkdV3Hphii9AoGBAJlYlIsJCnksvkmB6/yS" +
          "4Qjl9bIxRQR+/awJnA9FE8mlzoPAbIHGZ+UGBYX3anmuHsaRS+D1t8AUEIl/3c0s" +
          "+RAbvriI0KuCQCZ0bWmUpDB7NQ+mgaj9lj2pBDB1RsaUxflVHQUXrsHhwp8KSbXI" +
          "gkgS6o41NZ8MAxmDtsMlvCII";


  public static String sign(String message) throws Exception {
    byte[] messageBytes = message.getBytes("UTF-8");

    // 解析私钥
    byte[] privateKeyBytes = Base64.getDecoder().decode(privateKey);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey priKey = keyFactory.generatePrivate(keySpec);

    // 使用私钥对消息进行签名
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(priKey);
    signature.update(messageBytes);
    byte[] signBytes = signature.sign();

    // 对签名结果进行 Base64 编码
    return Base64.getEncoder().encodeToString(signBytes);
  }

  public static String decryptResource(String ciphertext, String key, String nonce, String associatedData) {
    try {
      // Base64解码
      byte[] decodedCipherText = Base64.getDecoder().decode(ciphertext);
      // 解密密钥
      byte[] decodedKey = key.getBytes(StandardCharsets.UTF_8);
      SecretKey secretKey = new SecretKeySpec(decodedKey, "AES");
      // 初始化GCM参数
      GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, nonce.getBytes(StandardCharsets.UTF_8));
      // 初始化Cipher
      Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
      cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
      // 设置关联数据
      cipher.updateAAD(associatedData.getBytes(StandardCharsets.UTF_8));
      // 解密数据
      byte[] decryptedBytes = cipher.doFinal(decodedCipherText);
      return new String(decryptedBytes, StandardCharsets.UTF_8);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
//
//  // 解密测试
//  public static void main(String[] args) {
//    // 提供的加密资源
//    String ciphertext = "81qop3lmI0dUFxRgMZQrWLSdoCo4W3xBTnDzfKGC8FywMXHa6sUXbvus+heBL/Q18Wv8a338/nHyXZ0ogl0VJyLOuhGiWfYKOA2YXP010Sdnf5/TimEl7N6Sgb47ajry46N/BtAc1Hb72OjCstqkonEDoW+yRWGmH3voWstuPpLONuO8mFq60xDLclxFy4gpDTt0tnW/uXZL2jhTFvXRcaQKXnsskvR8mCQjClm+pW8ZSHWiS1EEGeCjytj/OWx8ACmiR4bWRU8VZzSchy9E3kKmSqC1KEze9V0YTk9m9g9LWvjcqjbdVnP1OBvAKulASvYgFlVW2Vnb4kpvNo4v7wW499I0kHMPKXfgP2HCcpI7NCLwC7OunP/enyr5yS84kHQvBqigSm/bb64D4ZCtQhopl+KtZMPCJ64C9lGCyL5fU3l0FkG2JQ7pYkLM8X9tBsHgQdUvJ6g55/2xciBgho1OAKcJ1bJpJZIZvauBX7Za9KG4rr2loJwgGTsYGRe/xyOjG86XaPZjcsnWzY4pTqBPTKfHqX/qx4qqIHNuU0rH0w4Sw6Dy2F6MvKe86i/k2sQhFnfP";
//    // 解密密钥（需要根据实际情况设置）
//    String key = "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";
//    // 相关数据
//    String associatedData = "transaction";
//    // nonce
//    String nonce = "RHpMkQjhlTzp";
//
//    // 解密数据
//    String decryptedResource = decryptResource(ciphertext, key, nonce, associatedData);
//    System.out.println("Decrypted Resource: " + decryptedResource);
//  }


//  加密测试
//  public static void main(String[] args) {
//    // 创建 WxMiniProgramSigner 实例
//    WxMiniProgramSigner signer = new WxMiniProgramSigner();
//
//    long timestamp = Instant.now().getEpochSecond();
//    String nonce = NonceUtil.createNonce(32);
//    String packageVal = "prepay_id=" + "prepayId";
//    // 拼接字符串
//    String message = APP_ID + "\n" + timestamp + "\n" + nonce + "\n" + packageVal + "\n";
//    // 待签名的消息
////    String message = "YOUR_APP_ID\nTIMESTAMP\nNONCE\nYOUR_PACKAGE_VAL\n"; // 请替换为实际的参数值
//
//    try {
//      // 生成签名
//      String sign = signer.sign(message);
//      System.out.println("生成的签名值为：" + sign);
//    } catch (Exception e) {
//      System.err.println("生成签名时出现异常：" + e.getMessage());
//    }
//  }
}